// 添加轮播图
import { Space, Input, Button, Image, message } from 'antd';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { addBanner } from '../../api/banner';

type AddProps = {}
export const Add = (props: AddProps) => {
    const [alt,setAlt] = useState<string>('')
    const [link,setLink] = useState<string>('')
    const [url,setUrl] = useState('')

    // 获取上传文件的相关内容
    const getImgUrl = () => {
        const img = document.getElementById('img') as HTMLInputElement
        const files = img && img.files
        const file = files && files[0]
        // 读取
        const reader = new FileReader()
        reader.readAsDataURL(file!)
        // 读取成功之后调用
        reader.onload = function () {
            setUrl(this.result!.toString())
        }
    }
    const navigate = useNavigate()

    return(
        <Space direction='vertical' style={{width:300}}>
            <Input placeholder='提示信息' value={alt} onChange={e => setAlt(e.target.value)}></Input>
            <Input placeholder='链接地址' value={link} onChange={e => setLink(e.target.value)}></Input>
            <Input type='file' id='img' onChange={getImgUrl}></Input>
            <div>
                预览图片：
                <Image src={url} width={300}></Image>
            </div>
            <Button type='primary'  onClick={() => {
                if(alt === '' || link === '' || url === '') {
                    message.error('请输入')
                    return
                }
                addBanner({
                    alt,link,img:url
                }).then(() => {
                    navigate('/banner/home')
                })
            }}>
                添加
            </Button>

        </Space>
    )
}